package com.ms.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.log4j.Logger;

/**
 * 拼音
 * @author User
 *
 */
public class PYUtil {
	
	private static Logger logger = Logger.getLogger(PYUtil.class);
	
	/**
	 * 得到字符串对应的拼音
	 * @param src
	 * @return
	 */
	public static String getPinYin(String src) {
		StringBuilder pinyinBuf = new StringBuilder();
		HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
		outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

		try {
			for (int i = 0; i < src.length(); i++) {
				String[] pinYins = PinyinHelper.toHanyuPinyinStringArray(src.charAt(i), outputFormat);
				if (pinYins != null && pinYins.length > 0) {// 汉语
					pinyinBuf.append(pinYins[0].charAt(0));
				} else {// 非汉语
					pinyinBuf.append(src.charAt(i));
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			logger.error(e.getMessage(), e);
		}
		return pinyinBuf.toString();
	}
}
